package com.uyun.rbac.permission.dao.impl;

import com.uyun.rbac.permission.dao.PermissionDao;
import com.uyun.rbac.permission.entity.MenuEntity;
import com.uyun.rbac.permission.entity.PermissionEntity;
import com.uyun.rbac.permission.entity.RoleEntity;
import com.uyun.util.AppUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Repository(value="permissionDao")
public class PermissionDaoImpl implements PermissionDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;


    /** for permission page **/

    @Override
    public List<PermissionEntity> getPermissionListForPage(Map<String, String> paraMap){

        String permissionName =  paraMap.get("permissionName");
        String url =  paraMap.get("url");
        String mapping =  paraMap.get("mapping");

        StringBuilder sb = new StringBuilder();
        List<Object> listStr = new ArrayList<>();

        if(AppUtils.StringUtil(permissionName)!=null){
            sb.append(" and name  like  ? ");
            listStr.add("%"+permissionName+"%");// 全匹配无法用到索引
        }

        if(AppUtils.StringUtil(url)!=null){
            sb.append(" and url  like  ? ");
            listStr.add("%"+url+"%");
        }

        if(AppUtils.StringUtil(mapping)!=null){
            sb.append(" and mapping  like  ? ");
            listStr.add("%"+mapping+"%");
        }

        String sql = " select id from  permission where 1=1  ";
        sb.append("order by name");

        List<Integer> permissionIds = jdbcTemplate.queryForList(sql+sb.toString(),Integer.class,listStr.toArray());

        List<PermissionEntity> dataList = new ArrayList<>();

        permissionIds.stream().forEach(id->dataList.add(getPermissionEntityById(id)));

        return dataList;

    }


    @Override
    public boolean addPermissionEntity(PermissionEntity entity){

        int count ;

        try{
            count  = jdbcTemplate.update("insert into  permission(name,mapping,type,url)" +
                    " values(?,?,?,?) ",entity.getName(),entity.getMapping(),entity.getType(),entity.getUrl());
        }catch (Exception e){
            return false;
        }

        return count > 0;


    }


    /** for role page **/
    @Override
    public List<RoleEntity> getRoleListForPage(Map<String, String> paraMap){

        String roleName =  paraMap.get("roleName");

        StringBuilder sb = new StringBuilder();
        List<Object> listStr = new ArrayList<>();

        if(AppUtils.StringUtil(roleName)!=null){
            sb.append(" and rolename  like  ? ");
            listStr.add("%"+roleName+"%");
        }

        String sql = " select id from  role where 1=1 ";

        List<Integer> roleIds = jdbcTemplate.queryForList(sql+sb.toString(),Integer.class,listStr.toArray());

        List<RoleEntity> dataList = new ArrayList<>();

        roleIds.stream().forEach(id->dataList.add(getRoleEntityById(id)));

        return dataList;

    }

    @Override
    public void clearRoleHasMenu(int roleId){

        jdbcTemplate.update("delete from  role_menu where roleid=? ",roleId);

    }

    @Override
    public void addRoleHasMenu(int roleId,int menuId){

        try{
            jdbcTemplate.update("insert into  role_menu(roleid,menuid) values(?,?) ",roleId,menuId);
        }catch (Exception ignored){}

    }

    @Override
    public void clearRoleHasPerm(int roleId){

        jdbcTemplate.update("delete from  role_permission where roleid=? ",roleId);

    }

    @Override
    public void addRoleHasPerm(int roleId,int permId){

        try{
             jdbcTemplate.update("insert into  role_permission(roleid,permissionid) values(?,?) ",roleId,permId);
        }catch (Exception ignored){
        }

    }







    /********else**********/

    @Override
    public RoleEntity getRoleEntityById(int id){

        RoleEntity roleEntity = new RoleEntity();

        jdbcTemplate.query("select id,rolename from  role where id=? ",(ResultSet rs )->{

            roleEntity.setId(rs.getInt("id"));
            roleEntity.setRoleName(rs.getString("rolename"));
            List<PermissionEntity> list_permissionEntities = new ArrayList<>();
            List<MenuEntity> list_menuEntities = new ArrayList<>();


            jdbcTemplate.query("select permissionid from  permission p " +
                    "LEFT JOIN  role_permission rp on rp.permissionid=p.id where  rp.roleid=? ",(ResultSet innerRs)->{

                int permissionId = innerRs.getInt("permissionid");
                PermissionEntity permissionEntity = getPermissionEntityById(permissionId);

                list_permissionEntities.add(permissionEntity);

            },id);


            jdbcTemplate.query("select  menuid from  menu m " +
                    "LEFT JOIN  role_menu rm on rm.menuid=m.id where  rm.roleid=? ",(ResultSet innerRs)->{

                int menuId = innerRs.getInt("menuid");
                MenuEntity menuEntity = getMenuEntityById(menuId);

                list_menuEntities.add(menuEntity);

            },id);


           for(MenuEntity menuEntity:list_menuEntities){
                AppUtils.buildTree(list_menuEntities,menuEntity);
            }

            roleEntity.setMenuEntityList(list_menuEntities.stream().filter(entity -> entity.getPid() == null||entity.getPid()==0).collect(Collectors.toList()));
            roleEntity.setPermissionEntityList(list_permissionEntities);

        },id);

        return roleEntity;

    }



    @Override
    public PermissionEntity getPermissionEntityById(int id){

        PermissionEntity entity = new PermissionEntity();

        jdbcTemplate.query("select * from  permission where id=? ",(ResultSet rs )->{

            entity.setId(rs.getInt("id"));
            entity.setName(rs.getString("name"));
            entity.setUrl(rs.getString("url"));
            entity.setMapping(rs.getString("mapping"));
            entity.setType(rs.getInt("type"));

        },id);

        return entity;

    }


    @Override
    public List<Integer> getAllPermissionIds(){

        return jdbcTemplate.queryForList("select id from permission",java.lang.Integer.class);
    }


    /**
     * for webapp init
     * @return
     */
    @Override
    public List<Integer> getAllRoleIds(){
        return jdbcTemplate.queryForList("select id from  role",Integer.class);
    }


    /***menu ***/

    @Override
    public MenuEntity getMenuEntityById(int id) {

        MenuEntity entity = new MenuEntity();

        jdbcTemplate.query("select pid,id,name,url from  menu where id =?  ",(ResultSet rs )->{
            int pid = rs.getInt("pid");
            String name  = rs.getString("name");
            String url = rs.getString("url");
            entity.setPid(pid);
            entity.setId(id);
            entity.setName(name);
            entity.setUrl(url);},id);

        return entity;

    }


	@Override
	public List<MenuEntity> getAllMenuList() {

        List<MenuEntity> list= new ArrayList<>();

        jdbcTemplate.query("select pid,id,name,url from  menu ",(ResultSet rs )->{
            int pid = rs.getInt("pid");
            int id = rs.getInt("id");
            String name  = rs.getString("name");
            String url = rs.getString("url");
            MenuEntity entity = new MenuEntity();
            entity.setPid(pid);
            entity.setId(id);
            entity.setName(name);
            entity.setUrl(url);
            list.add(entity);
        });
		return list;
	}


	
}
